module SessionsHelper

	def current_user
		# 判断是否在会话中
		if(user_id=session[:user_id])
			@current_user||=User.find_by(id: user_id)			# 会话中取出用户
		else(user_id=cookies.signed[:user_id])		# cookies中存在否
			user ||=User.find_by(id: user_id)
			if(user && user.authenticated?(:remember,cookies[:remember_token]))		# 存在验证
				login user
				@current_user=user
			end
		end
	end

	def log_in(user)
		session[:user_id] = user.id
	end
	def is_loged_in?
		!current_user.nil?
	end

	def log_in_user
		unless is_loged_in?
		  flash[:warning]='请登陆fasfaasdfsaf'
			redirect_to login_url
		end
	end

	def is_current_user?(user)
		user==current_user
	end
	def rememberme(user)
		user.remember
		cookies.permanent[:remember_token]=user.remember_token
		cookies.permanent.signed[:user_id]=user.id
	end



	def logout
		forget(current_user)
		session.delete(:user_id)
		@current_user=nil
	end

	def redirect_or_back(default)
		redirect_to (session[:forwarding_url]||default)
		session.delete(:forwarding_url)
	end
	def forget(user)
		user.forget
		# 销毁数据库中的令牌
		# cookies.permanent[:remember_token]=nil
		# cookies.permanent.signed[:user_id]=nil
		cookies.delete(:remember_token)
		cookies.delete(:user_id)
	end
	def correct_user
		@user=User.find(params[:id])
		redirect_to (root_url) unless is_current_user?(@user)

	end



end
